#!/usr/bin/env pwsh

# 学生管理系统数据库连接测试脚本

Write-Host "=== 学生管理系统数据库连接测试 ==="

# 设置数据库连接参数
$mysqlHost = "localhost"
$mysqlPort = "3306"
$mysqlDatabase = "StudentManagementDB"
$mysqlUser = "root"
$mysqlPassword = "123456"

# 检查MySQL客户端是否安装
$mysqlClient = Get-Command mysql -ErrorAction SilentlyContinue
if (-not $mysqlClient) {
    Write-Host "错误: 未找到MySQL客户端。请确保已安装MySQL并将其添加到系统PATH。"
    Write-Host "测试失败！"
    exit 1
}

# 构建连接字符串
$connectionString = "-h $mysqlHost -P $mysqlPort -u $mysqlUser -p$mysqlPassword -D $mysqlDatabase"

# 测试数据库连接
Write-Host "正在测试数据库连接..."
try {
    # 执行简单查询测试连接
    $queryResult = mysql $connectionString -e "SELECT VERSION();" 2>$null
    
    if ($LASTEXITCODE -eq 0) {
        Write-Host "✓ 数据库连接成功!"
        Write-Host "MySQL 版本: $($queryResult[1])"
        
        # 检查数据库表是否存在
        Write-Host "\n检查数据库表结构..."
        $tables = mysql $connectionString -e "SHOW TABLES;" 2>$null
        
        if ($tables.Count -gt 1) {
            Write-Host "✓ 数据库包含 $($tables.Count - 1) 个表："
            $tables | Select-Object -Skip 1 | ForEach-Object { Write-Host "  - $_" }
            
            # 检查初始数据是否已加载
            Write-Host "\n检查初始数据..."
            
            # 检查角色表数据
            $rolesCount = mysql $connectionString -e "SELECT COUNT(*) FROM roles;" 2>$null
            $rolesCount = $rolesCount -split "\s+" | Where-Object { $_ -match "\d+" }
            Write-Host "✓ 角色表包含 $rolesCount 条记录"
            
            # 检查用户表数据
            $usersCount = mysql $connectionString -e "SELECT COUNT(*) FROM users;" 2>$null
            $usersCount = $usersCount -split "\s+" | Where-Object { $_ -match "\d+" }
            Write-Host "✓ 用户表包含 $usersCount 条记录"
            
            # 检查班级表数据（如果有）
            $classesCount = mysql $connectionString -e "SELECT COUNT(*) FROM classes;" 2>$null
            $classesCount = $classesCount -split "\s+" | Where-Object { $_ -match "\d+" }
            Write-Host "✓ 班级表包含 $classesCount 条记录"
            
            Write-Host "\n数据库测试完成！所有测试都通过。"
            Write-Host "系统已准备就绪，可以开始使用。"
            exit 0
        } else {
            Write-Host "错误: 数据库中未找到表。请运行初始化脚本。"
            Write-Host "使用命令: mysql -u root -p < init.sql"
            Write-Host "测试失败！"
            exit 1
        }
    } else {
        Write-Host "错误: 数据库连接失败。请检查连接参数和MySQL服务状态。"
        Write-Host "可能的问题："
        Write-Host "1. MySQL服务未启动"
        Write-Host "2. 用户名或密码错误"
        Write-Host "3. 数据库不存在"
        Write-Host "测试失败！"
        exit 1
    }
} catch {
    Write-Host "错误: 发生异常 - $($_.Exception.Message)"
    Write-Host "测试失败！"
    exit 1
}